// Web3钱包服务
class Web3WalletService {
  constructor() {
    this.provider = null;
    this.web3 = null;
    this.account = null;
    this.chainId = null;
    this.isConnected = false;
    this.i18n = null; // 国际化实例
    
    // 地址变化监听相关
    this.addressChangeCallbacks = []; // 地址变化回调函数数组
  }

  // 设置国际化实例
  setI18n(i18n) {
    this.i18n = i18n;
  }

  // 获取翻译文本
  t(key) {
    if (this.i18n) {
      return this.i18n.t(`wallet.${key}`);
    }
    // 如果没有i18n实例，返回默认中文
    const defaultMessages = {
      'connect': '连接钱包',
      'disconnect': '断开',
      'connecting': '连接中...',
      'connect_success': '钱包连接成功',
      'connect_failed': '连接失败',
      'connect_error': '连接失败，请检查钱包',
      'disconnect_success': '已断开连接',
      'no_metamask': '未检测到MetaMask或其他Web3钱包',
      'user_rejected': '用户拒绝了连接请求',
      'wallet_not_connected': '钱包未连接',
      'auto_connect_success': '自动连接钱包成功',
      'auto_connect_failed': '自动连接失败',
      'check_wallet_failed': '检查钱包状态失败',
      'switch_network_failed': '切换到BSC网络失败',
      'add_network_failed': '添加BSC网络失败',
      'switch_to_bsc': '请切换到BSC网络',
      'auto_switch_failed': '自动切换BSC网络失败'
    };
    return defaultMessages[key] || key;
  }

  // 注册地址变化回调
  onAddressChange(callback) {
    if (typeof callback === 'function') {
      this.addressChangeCallbacks.push(callback);
    }
  }

  // 移除地址变化回调
  offAddressChange(callback) {
    const index = this.addressChangeCallbacks.indexOf(callback);
    if (index > -1) {
      this.addressChangeCallbacks.splice(index, 1);
    }
  }

  // 触发地址变化回调
  triggerAddressChange(oldAccount, newAccount) {
    console.log('钱包地址变化:', { oldAccount, newAccount });
    console.log('注册的回调函数数量:', this.addressChangeCallbacks.length);
    this.addressChangeCallbacks.forEach((callback, index) => {
      try {
        console.log(`执行回调函数 ${index}:`, callback);
        callback(oldAccount, newAccount);
      } catch (error) {
        console.error('地址变化回调执行失败:', error);
      }
    });
  }

  // 检查是否支持Web3
  async checkWeb3Support() {
    if (typeof window !== 'undefined' && window.ethereum) {
      return true;
    }
    return false;
  }

  // 强制检查当前钱包地址（页面重新进入时调用）
  async forceCheckWalletAddress() {
    try {
      console.log('开始强制检查钱包地址...');
      
      if (!await this.checkWeb3Support()) {
        console.log('Web3不支持，跳过强制检查');
        return { changed: false, account: null };
      }

      const accounts = await window.ethereum.request({
        method: 'eth_accounts'
      });

      const currentAccount = accounts.length > 0 ? accounts[0] : null;
      const hasChanged = this.account !== currentAccount;

      console.log('强制检查结果:', {
        currentAccount,
        previousAccount: this.account,
        hasChanged
      });

      if (hasChanged) {
        const oldAccount = this.account;
        this.account = currentAccount;
        
        if (currentAccount) {
          this.isConnected = true;
          // 触发地址变化回调
          this.triggerAddressChange(oldAccount, currentAccount);
        } else {
          this.isConnected = false;
          // 触发断开连接回调
          this.triggerAddressChange(oldAccount, null);
        }
      }

      return { 
        changed: hasChanged, 
        account: currentAccount,
        previousAccount: this.account
      };

    } catch (error) {
      console.error('强制检查钱包地址失败:', error);
      return { changed: false, account: null, error: error.message };
    }
  }

  // 自动连接钱包
  async autoConnect() {
    try {
      if (!await this.checkWeb3Support()) {
        return {
          success: false,
          error: this.t('no_metamask')
        };
      }

      // 检查是否已经连接
      const accounts = await window.ethereum.request({
        method: 'eth_accounts'
      });

      if (accounts.length > 0) {
        // 已经连接，直接获取账户信息
        this.account = accounts[0];
        
        // 检查并切换网络
        const chainId = await window.ethereum.request({
          method: 'eth_chainId'
        });

        if (chainId !== '0x38' && chainId !== '0x61') {
          try {
            await this.switchToBSC();
            this.chainId = await window.ethereum.request({
              method: 'eth_chainId'
            });
          } catch (error) {
            console.warn(this.t('auto_switch_failed'), error);
            this.chainId = chainId;
          }
        } else {
          this.chainId = chainId;
        }

        this.isConnected = true;

        // 设置事件监听
        this.setupEventListeners();

        // 手动触发地址变化回调（自动连接时）
        console.log('🔄 自动连接成功，手动触发地址变化回调');
        this.triggerAddressChange(null, this.account);

        return {
          success: true,
          account: this.account,
          chainId: this.chainId
        };
      }

      return {
        success: false,
        error: this.t('wallet_not_connected')
      };

    } catch (error) {
      console.error(this.t('auto_connect_failed'), error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 设置事件监听
  setupEventListeners() {
    if (!window.ethereum) return;

    // 监听账户变化
    window.ethereum.on('accountsChanged', (accounts) => {
      console.log('检测到账户变化事件:', accounts);
      
      if (accounts.length === 0) {
        // 钱包断开连接
        this.disconnect();
      } else {
        // 账户切换
        const oldAccount = this.account;
        this.account = accounts[0];
        this.isConnected = true;
        
        // 触发地址变化回调
        this.triggerAddressChange(oldAccount, this.account);
      }
    });

    // 监听链变化
    window.ethereum.on('chainChanged', (chainId) => {
      console.log('检测到链变化事件:', chainId);
      this.chainId = chainId;
      if (chainId !== '0x38' && chainId !== '0x61') {
        // 自动切换回BSC网络
        this.switchToBSC().catch(error => {
          console.warn('自动切换BSC网络失败:', error);
        });
      }
    });

    // 监听断开连接
    window.ethereum.on('disconnect', (error) => {
      console.log('检测到钱包断开连接:', error);
      this.disconnect();
    });

    console.log('钱包事件监听器已设置');
  }

  // 连接BSC链
  async connectBSC() {
    try {
      if (!await this.checkWeb3Support()) {
        throw new Error(this.t('no_metamask'));
      }

      // 请求连接钱包
      const accounts = await window.ethereum.request({
        method: 'eth_requestAccounts'
      });

      if (accounts.length === 0) {
        throw new Error(this.t('user_rejected'));
      }

      this.account = accounts[0];
      
      // 检查当前网络
      const chainId = await window.ethereum.request({
        method: 'eth_chainId'
      });

      // BSC主网chainId: 0x38 (56)
      // BSC测试网chainId: 0x61 (97)
      if (chainId !== '0x38' && chainId !== '0x61') {
        // 自动切换到BSC主网
        try {
          await this.switchToBSC();
          // 重新获取切换后的chainId
          this.chainId = await window.ethereum.request({
            method: 'eth_chainId'
          });
        } catch (error) {
          console.warn(this.t('switch_network_failed'), error);
          this.chainId = chainId;
        }
      } else {
        this.chainId = chainId;
      }

      this.isConnected = true;

      // 设置事件监听
      this.setupEventListeners();

      // 手动触发地址变化回调（从无地址到有地址）
      console.log('🔗 连接成功，手动触发地址变化回调');
      this.triggerAddressChange(null, this.account);

      return {
        success: true,
        account: this.account,
        chainId: this.chainId
      };

    } catch (error) {
      console.error('连接BSC失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 切换到BSC网络
  async switchToBSC() {
    try {
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: '0x38' }], // BSC主网
      });
    } catch (switchError) {
      // 如果网络不存在，则添加网络
      if (switchError.code === 4902) {
        await this.addBSCNetwork();
      } else {
        throw switchError;
      }
    }
  }

  // 添加BSC网络
  async addBSCNetwork() {
    try {
      await window.ethereum.request({
        method: 'wallet_addEthereumChain',
        params: [{
          chainId: '0x38',
          chainName: 'Binance Smart Chain',
          nativeCurrency: {
            name: 'BNB',
            symbol: 'BNB',
            decimals: 18
          },
          rpcUrls: ['https://bsc-dataseed.binance.org/'],
          blockExplorerUrls: ['https://bscscan.com/']
        }]
      });
    } catch (error) {
      throw new Error(this.t('add_network_failed'));
    }
  }

  // 断开连接
  disconnect() {
    const oldAccount = this.account;
    
    this.provider = null;
    this.web3 = null;
    this.account = null;
    this.chainId = null;
    this.isConnected = false;
    
    // 触发断开连接回调
    this.triggerAddressChange(oldAccount, null);
    
    console.log('钱包已断开连接');
  }

  // 获取当前账户
  getCurrentAccount() {
    return this.account;
  }

  // 获取当前网络
  getCurrentChainId() {
    return this.chainId;
  }

  // 检查是否已连接
  isWalletConnected() {
    return this.isConnected && this.account;
  }

  // 格式化地址显示
  formatAddress(address, start = 6, end = 4) {
    if (!address) return '';
    return `${address.slice(0, start)}...${address.slice(-end)}`;
  }

  // 获取账户余额
  async getBalance() {
    if (!this.isConnected || !this.account) {
      throw new Error(this.t('wallet_not_connected'));
    }

    try {
      const balance = await window.ethereum.request({
        method: 'eth_getBalance',
        params: [this.account, 'latest']
      });

      // 将wei转换为BNB
      const balanceInBNB = parseInt(balance, 16) / Math.pow(10, 18);
      return balanceInBNB.toFixed(4);
    } catch (error) {
      console.error('获取余额失败:', error);
      throw error;
    }
  }

  // USDT合约地址 (BSC主网)
  getUSDTContractAddress() {
    return '0x55d398326f99059fF775485246999027B3197955'; // BSC主网USDT合约地址
  }

  // USDT转账方法
  async transferUSDT(toAddress, amount) {
    console.log('transferUSDT被调用，参数:', { toAddress, amount });
    
    if (!this.isConnected || !this.account) {
      console.log('钱包连接检查失败:', { isConnected: this.isConnected, account: this.account });
      throw new Error(this.t('wallet_not_connected'));
    }
    console.log('钱包连接状态正常，账户:', this.account);

    try {
      // USDT合约的transfer方法签名
      const transferMethodSignature = '0xa9059cbb';
      
      // 将地址转换为32字节格式（去掉0x前缀，补齐到64位）
      const toAddressPadded = toAddress.slice(2).padStart(64, '0');
      
      // 将金额转换为wei格式（BSC上的USDT使用18位小数）
      console.log('转账金额转换详情:', {
        原始金额: amount,
        金额类型: typeof amount,
        转换为wei: amount * Math.pow(10, 18),
        wei十六进制: (amount * Math.pow(10, 18)).toString(16)
      });
      const amountInWei = (amount * Math.pow(10, 18)).toString(16);
      const amountPadded = amountInWei.padStart(64, '0');
      
      // 构建交易数据
      const data = transferMethodSignature + toAddressPadded + amountPadded;
      console.log('构建的交易数据:', {
        transferMethodSignature,
        toAddressPadded,
        amountPadded,
        data
      });

      // 获取当前gas价格
      console.log('获取gas价格...');
      const gasPrice = await window.ethereum.request({
        method: 'eth_gasPrice'
      });
      console.log('gas价格:', gasPrice);

      // 估算gas限制
      console.log('估算gas限制...');
      const gasLimit = await window.ethereum.request({
        method: 'eth_estimateGas',
        params: [{
          from: this.account,
          to: this.getUSDTContractAddress(),
          data: data
        }]
      });
      console.log('gas限制:', gasLimit);

      // 发送交易
      const transactionParameters = {
        to: this.getUSDTContractAddress(),
        from: this.account,
        data: data,
        gas: gasLimit,
        gasPrice: gasPrice
      };
      console.log('交易参数:', transactionParameters);

      console.log('发送交易到钱包...');
      const txHash = await window.ethereum.request({
        method: 'eth_sendTransaction',
        params: [transactionParameters]
      });
      console.log('交易发送成功，哈希:', txHash);

      return {
        success: true,
        txHash: txHash,
        message: 'USDT转账交易已发送'
      };

    } catch (error) {
      console.error('USDT转账失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 获取USDT余额
  async getUSDTBalance(address = null) {
    console.log('getUSDTBalance被调用，参数:', { address, currentAccount: this.account });
    
    if (!this.isConnected || !this.account) {
      throw new Error(this.t('wallet_not_connected'));
    }

    try {
      const targetAddress = address || this.account;
      console.log('目标地址:', targetAddress);
      
      // USDT合约的balanceOf方法签名
      const balanceOfMethodSignature = '0x70a08231';
      
      // 将地址转换为32字节格式
      const addressPadded = targetAddress.slice(2).padStart(64, '0');
      
      // 构建查询数据
      const data = balanceOfMethodSignature + addressPadded;
      console.log('查询数据:', { balanceOfMethodSignature, addressPadded, data });

      // 调用合约方法
      const result = await window.ethereum.request({
        method: 'eth_call',
        params: [{
          to: this.getUSDTContractAddress(),
          data: data
        }, 'latest']
      });
      console.log('合约调用结果:', result);

      // 将结果转换为数字（BSC上的USDT使用18位小数）
      const balanceInWei = parseInt(result, 16);
      const balanceInUSDT = balanceInWei / Math.pow(10, 18);
      console.log('余额转换:', { balanceInWei, balanceInUSDT });
      
      // 检查余额是否合理
      if (balanceInUSDT > 1000000) {
        console.warn('USDT余额异常，可能合约地址或小数位数错误');
        // 尝试使用6位小数重新计算（兼容其他网络）
        const balanceInUSDT6 = balanceInWei / Math.pow(10, 6);
        console.log('使用6位小数重新计算:', balanceInUSDT6);
        return balanceInUSDT6.toFixed(2);
      }
      
      // 检查余额是否为NaN或无效值
      if (isNaN(balanceInUSDT) || balanceInUSDT < 0) {
        console.warn('USDT余额无效，返回0');
        return '0.00';
      }
      
      return balanceInUSDT.toFixed(2);

    } catch (error) {
      console.error('获取USDT余额失败:', error);
      throw error;
    }
  }

  // 等待交易确认
  async waitForTransaction(txHash) {
    try {
      // 等待交易被挖矿
      const receipt = await window.ethereum.request({
        method: 'eth_getTransactionReceipt',
        params: [txHash]
      });

      if (receipt && receipt.status === '0x1') {
        return {
          success: true,
          receipt: receipt,
          message: '交易确认成功'
        };
      } else if (receipt && receipt.status === '0x0') {
        return {
          success: false,
          error: '交易失败'
        };
      } else {
        // 交易还在处理中，等待一段时间后重试
        await new Promise(resolve => setTimeout(resolve, 3000));
        return this.waitForTransaction(txHash);
      }
    } catch (error) {
      console.error('等待交易确认失败:', error);
      throw error;
    }
  }

  // 检查交易状态
  async checkTransactionStatus(txHash) {
    try {
      const receipt = await window.ethereum.request({
        method: 'eth_getTransactionReceipt',
        params: [txHash]
      });

      if (!receipt) {
        return 'pending'; // 交易还在处理中
      }

      if (receipt.status === '0x1') {
        return 'success'; // 交易成功
      } else {
        return 'failed'; // 交易失败
      }
    } catch (error) {
      console.error('检查交易状态失败:', error);
      return 'error';
    }
  }

  // 签名消息（用于登录验证）
  async signMessage(message, address) {
    try {
      if (!this.isConnected || !this.account) {
        throw new Error(this.t('wallet_not_connected'));
      }

      if (address && address.toLowerCase() !== this.account.toLowerCase()) {
        throw new Error('签名地址与当前连接地址不匹配');
      }

      console.log('开始签名消息:', { message, address: this.account });

      // 使用 personal_sign 方法签名
      const signature = await window.ethereum.request({
        method: 'personal_sign',
        params: [message, this.account]
      });

      console.log('签名成功:', signature);

      return {
        success: true,
        signature: signature,
        message: message,
        address: this.account
      };

    } catch (error) {
      console.error('签名失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 生成登录消息
  generateLoginMessage(address) {
    const timestamp = Date.now();
    const message = ` XGT SINGLE\nTimestamp: ${timestamp}\nAddress: ${address}`;
    return message;
  }
}

// 创建单例实例
const web3WalletService = new Web3WalletService();

export default web3WalletService;
